#!/usr/bin/env python
#coding=utf-8

import redis
import pickle
from flask import current_app

class Redis(object):
    """Redis读写"""
    def __init__(self):
        super(Redis, self).__init__()


    @classmethod
    def connect(cls):
        cls.REDIS_HOST     = current_app.config.get('REDIS_HOST', '')
        cls.REDIS_PORT     = current_app.config.get('REDIS_PORT', '')
        cls.REDIS_DBNAME   = current_app.config.get('REDIS_DBNAME', '')
        cls.REDIS_USERNAME = current_app.config.get('REDIS_USERNAME', '')
        cls.REDIS_PASSWORD = current_app.config.get('REDIS_PASSWORD', '')
        cls.REDIS_ENABLE   = current_app.config.get('REDIS_ENABLE', 'False')
        cls.r              = redis.StrictRedis(host=cls.REDIS_HOST,
                                    port=cls.REDIS_PORT,
                                    db=cls.REDIS_DBNAME)
        return cls.r

    #将内存数据二进制通过序列号转为文本流，再存入redis
    @classmethod
    def set_data(cls, key, data, ex=None):
        r = cls.connect()
        if cls.REDIS_ENABLE == 'False':
            # 关闭redis
            return False

        r.set(key, pickle.dumps(data), ex)
        return True

    # 将文本流从redis中读取并反序列化，返回返回
    @classmethod
    def get_data(cls, key):
        r = cls.connect()
        if cls.REDIS_ENABLE == 'False':
            # 关闭redis
            return False

        data = r.get(key)
        if data is None:
            return None

        return pickle.loads(data)

    @classmethod
    def delete_data(cls, *key):
        if cls.REDIS_ENABLE == 'False':
            # 关闭redis
            return False

        for k in key:
            r = cls.r.get_data(k)
            if r:
                cls.r.delete(k)
        return True
